import type { FormInstance } from 'element-plus'
import { notify } from '@/utils/element'

interface Params {
  disableMounted?: boolean | Ref; // 其他组件可能disableMounted = false | ref(false);
  mustQuery?: any; // 查询条件，使用reactive创建的响应式变量，方便后期更新，可能存在固定的参数值
  getPageList: Function; // 查询列表的api方法
  deleteById?: Function; // 删除数据的api方法
}

/**
 * 针对分页列表组件实现逻辑
 * props：
 */
function useTablePage<T = any, Q = any>(params: Params, emit?: Function, props?: any) {
  // 列表ref
  const tableListRef = ref();

  // 编辑ref
  const editRef = ref();

  // 定义状态
  const state = reactive({
    loading: false,
    queryVisible: false,
    pageTypes: {
      current: 1, // 当前页码
      size: 20, // 每页显示多少条
      total: 0, // 总记录数
    } as PageType,
    query: {} as Q,
    tableList: [] as T[],
  });

  onMounted(() => {
    // 禁用首次加载，方便组件中其他位置触发加载列表
    if (unref(params.disableMounted)) return;
    queryData();
  });

  /**
   * 查询列表数据
   */
  function queryData() {
    // resolve正常处理完成后调用它，reject异常时调用它
    return new Promise((resolve, reject) => {
      state.loading = true;
      // 调用接口
      const pageParams = { current: state.pageTypes.current, size: state.pageTypes.size }
      // 合并必须传递的查询条件
      const query = params.mustQuery ? Object.assign({}, state.query, params.mustQuery) : state.query;

      params.getPageList(query, pageParams).then((resp: any) => {
        const { total, records } = resp.data;
        // console.log('records', records);

        state.tableList = []; // 清空
        nextTick(() => {
          // 总记录数
          state.pageTypes.total = total;
          // 列表数据
          state.tableList = records;
        });
        // 正常响应
        resolve(resp);
      }).catch((error: Error) => {
        // 异常情况
        reject(error);
      }).finally(() => {
        state.loading = false;
      });
    });
  }

  // 点击查询
  function handleQuery() {
    // 将页码设置为第1页
    state.pageTypes.current = 1;
    queryData();
  }

  // 点击删除
  async function handleDelete(id: string) {
    try {
      state.loading = true;
      if (params.deleteById) await params.deleteById(id);
      notify('删除成功！', { type: 'success' });
      queryData();
    } catch (error) {
    } finally {
      state.loading = false;
    }
  }

  // 点击新增
  function handleAdd(data?: any) {
    editRef.value?.open('add', '新增', data);
  }

  // 点击修改
  function handleEdit(row: T) {
    // console.log('row', row);
    editRef.value?.open('edit', '修改', row);
  }

  /** 
   * 重置查询 
   */
  const queryFormRef = ref<FormInstance>()
  function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
  }

  /**
   * 查询按钮
   */
  function filterButton() {
    state.queryVisible = !state.queryVisible
  }

  return {
    tableListRef,
    queryFormRef,
    editRef,
    ...toRefs(state),
    queryData,
    handleQuery,
    handleDelete,
    handleEdit,
    handleAdd,
    resetForm,
    filterButton,
  }

}

export default useTablePage;
export { useTablePage };